#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import datetime
import urllib
import urlparse
import re
import math
import codecs

from generator import *

import web

from PIL import Image
from cStringIO import StringIO

def GetImageWidth( x ):
    ua = web.ctx.env['HTTP_USER_AGENT'].lower()
    if ua.find('paneo') != -1:
        return 0 
    if ua.find('iphone') != -1:
        x = 640 
    elif ua.find('ipod') != -1:
        x = 640
    elif ua.find('android') != -1:
        x = 640 
    elif ua.find('ipad') != -1:
        x = 1280 
    else:
        x = 1536 
    return x

#from beaker.cache import CacheManager
#from beaker.util import parse_cache_config_options
#
#cache_opts = {
#    'cache.type': 'file',
#    'cache.data_dir': PANEO_SITE_DATA_DIR + '/_tmp/cache/data',
#    'cache.lock_dir': PANEO_SITE_DATA_DIR + '/_tmp/cache/lock'
#}
#cache = CacheManager(**parse_cache_config_options(cache_opts))

class View:

    def __init__(self):
        #web.header("Content-Type", "text/css; charset=UTF-8")
        #web.header("Cache-Control", "no-cache, must-revalidate")
        #web.header("Pragma", "no-cache")
        pass

    def GET( self, file = None , size = None):

        img_file = PANEO_SITE_DATA_DIR + 'img/' + file

        if size:
            xy = size.split('x')
            if len(xy) > 1 :
                x = int(xy[0])
                y = int(xy[1])
            else:
                x = size 
                y = x
        
            if not os.path.exists( img_file ):

                if os.path.exists( PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s' % ( size ) ):
                    img = open( PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s' % ( size ) ,"rb").read()
                    web.header("Content-Length", len(img))
                    return img
               
                try:
                    img = Image.new("RGB",(int(x),int(y)),"#e0e0e0")
                    img.save(PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s' % (size), "png")

                    fo = StringIO()
                    img.save(fo,"png")
                    web.header("Content-Type", "image/png; charset=UTF-8")
                    return fo.getvalue()
                except:
                    img = Image.new("RGB",(1,1),"#e0e0e0")
                    fo = StringIO()
                    img.save(fo,"png")
                    web.header("Content-Type", "image/png; charset=UTF-8")
                    return fo.getvalue()
        else:
            x = 0
            y = 0
            size = GetImageWidth(x)

        #try:
        if True:
            if x == 0:
                x = GetImageWidth(x)
                if x == 0:
                    img = open(img_file,"rb").read()
                    web.header("Content-Length", len(img))
                    #web.header("Content-Type", "image/%s; charset=UTF-8" % img.format)
                    return img


            if os.path.exists( PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s_%s' % ( file, size ) ):
                img = open( PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s_%s' % ( file, size ) ,"rb").read()
                web.header("Content-Type", "image/%s; charset=UTF-8" % img.format)
                web.header("Content-Length", len(img))
                return img


            try:
                img = Image.open(img_file) 
            except:
                return None

            if x == y or y == 0:
                xx = img.size[1]
                yy = img.size[0]
                sc = float(xx) / float(yy)
                y = int(x * sc)

            img.thumbnail( ( x,y ), Image.ANTIALIAS )

            #caching
            fo = StringIO()
            img.save(PANEO_SITE_DATA_DIR + '_tmp/cache/img/%s_%s' % ( file, size), img.format, quality=80)
            img.save(fo, img.format, quality=80)

            #web.header("Content-Length", len(fo))
            #web.header("Content-Type", "image/%s; charset=UTF-8" % img.format)
            return fo.getvalue()

        #except:
        #    img = open(img_file,"rb").read()
        #    web.header("Content-Length", len(img))
        #    return img


class ViewBackground:
    def GET( self, size=None, color="salmon"):
        try:
            x,y = size.split("x")
            x = int(x)
            y = int(y)
            img = Image.new("RGB",(x,y),color)
            fo = StringIO()
            img.save(fo,"png")
            web.header("Content-Type", "image/png; charset=UTF-8")
            return fo.getvalue()
        except:
            return None
        
class ViewPaneoImgDummy:

    def __init__(self):
        web.header("Content-Type", "text/png; charset=UTF-8")

    def GET( self, file = None ):
        return None 
